// 数据库管理

const ipconfig = require("../../config/ipconfig.js");
const client = require("../../db/db.js");
const getDataInfo = require("../../db/module/getDataInfo.js");
const readData = require("../../db/module/readData.js");
const writeData = require("../../db/module/writeData.js");
const delData = require("../../db/module/delData.js");
const fs = require("fs");
const express = require("express");
const multer = require("multer");

// 获取数据库对象（虽然已经在URI中指定，但这里可以再次确认）
const db = client.db(ipconfig.name);

// 注册路由
const apiRouter = express.Router();

// 上传文件中间件
const upload = multer({ dest: "uploads/" }); //文件上传的位置
const { saveFileData } = require("../../models/middleware.js");

// 获取数据库信息
apiRouter.post("/getDatBaseInfo", async (req, res) => {
  let parmse = req.body;
  try {
    // 列出数据库中的所有集合
    const collections = await db.listCollections().toArray();

    let newCollections = [];
    if (parmse.databaseName) {
      collections.forEach((item) => {
        if (item.name.includes(parmse.databaseName)) {
          newCollections.push(item);
        }
      });
    }

    if (newCollections.length == 0) {
      newCollections = collections;
    }

    let databaseInfos = [];
    for (let i = 0; i < newCollections.length; i++) {
      let item = newCollections[i];
      let result = await getDataInfo({}, item.name);
      if (result.code == 20000) {
        databaseInfos.push({
          size: (result.data.size / 1024 / 1024).toFixed(2) + "MB", //大小
          count: result.data.count, //条数
          storageSize: result.data.storageSize, //存储大小
          databaseName: item.name, // 数据库名称
        });
      }
    }

    // 将集合详细信息作为响应数据返回
    res.send({
      code: 20000,
      message: "获取数据库集合信息成功",
      data: databaseInfos,
    });
  } catch (error) {
    // 处理错误
    console.error("获取数据库集合信息时出错:", error);
    res.status(500).json({
      success: false,
      message: "获取数据库集合信息失败",
      error: error.message,
    });
  }
});

// 获取表所有数据
apiRouter.post("/getTableData", async (req, res) => {
  let parmse = req.body;
  let query = { ...parmse };
  delete query.databaseName;
  try {
    let result = await readData(
      {
        ...query,
      },
      parmse.databaseName
    );

    if (result.code == 20000) {
      res.send({
        code: 20000,
        data: result.data,
        total: result.total,
      });
    } else {
      res.send({
        code: 50000,
        msg: result.msg,
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: "系统异常，请联系管理员," + error,
    });
  }
});

// 修改保存表数据
apiRouter.post("/saveTableData", async (req, res) => {
  try {
    let parmse = req.body;

    let query = { ...parmse };
    delete query.databaseName;
    let result = await writeData({ ...query }, parmse.databaseName);
    if (result.code == 20000) {
      res.send({
        code: 20000,
        msg: "操作成功",
      });
    } else {
      res.send({
        code: 50000,
        msg: "操作失败",
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 删除表数据
apiRouter.post("/delTableData", async (req, res) => {
  try {
    let parmse = req.body;
    let query = { ...parmse };

    delete query.databaseName;
    let result = await delData({ ...query }, parmse.databaseName);
    if (result.code == 20000) {
      res.send({
        code: 20000,
        msg: "操作成功",
      });
    } else {
      res.send({
        code: 50000,
        msg: "操作失败",
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: error,
    });
  }
});

// 删除数据库
apiRouter.post("/deleteDatabase", async (req, res) => {
  try {
    let parmse = req.body;
    // 获取指定集合
    const collection = db.collection(parmse.databaseName);

    // 删除集合
    const result = await collection.drop();

    if (result) {
      res.send({
        code: 20000,
        msg: "操作成功",
      });
    } else {
      res.send({
        code: 50000,
        msg: "操作失败",
      });
    }
  } catch (error) {
    res.send({
      code: 50000,
      msg: "系统异常，请联系管理员",
    });
  }
});

// 新增数据库
apiRouter.post("/addDataBase", async (req, res) => {
  let params = req.body;
  try {
    let result = await db.createCollection(params.databaseName);

    res.send({
      code: 20000,
      msg: "操作成功",
    });
  } catch (error) {
    res.send({
      code: 50000,
      msg: "系统异常，请联系管理员",
    });
  }
});

// 导入数据库
apiRouter.post(
  "/uploadDatabase",
  upload.single("file"),
  saveFileData,
  async (req, res) => {
    let { databaseName } = req.body;

    // 获取刚才上传的数据，并且转为json格式
    let data = JSON.parse(
      fs.readFileSync("./uploads/" + req.file.filename).toString()
    );


    // 在数据库中写入数据
    try {
      let result = await writeData(data, databaseName, true);
      if (result.code == 20000) {
        res.send({
          code: 20000,
          msg: result.msg,
        });
      } else {
        res.send({
          code: 50000,
          msg: result.msg,
        });
      }
    } catch (error) {
      res.send({
        code: 50000,
        msg: "上传失败:" + error,
      });
    }
  }
);

module.exports = apiRouter;
